package wechat

import (
	"encoding/json"
	"fmt"
	"server/utils"

	"github.com/gin-gonic/gin"
	req "github.com/imroc/req"
)

func GetUserInfo(c *gin.Context) {
	code := c.Query("code")
	// code换取token： https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
	r, _ := req.Get("https://api.weixin.qq.com/sns/oauth2/access_token", req.Param{
		"appid":      "wxb86549d2232fa48d",
		"secret":     "a069fb164cc25ea91b9babdd0e994d58",
		"code":       code,
		"grant_type": "authorization_code",
	})

	var res map[string]interface{}
	r.ToJSON(&res)
	//拿到access_token {"access_token":"44_VZ_rxWSAyCKT4rGYaVq5atimQEUzv2CukEBHcmB0rObOU7NNMY7KoFNPsajVsAbes8Y6MKskft6f1A2gYhpXig", "expires_in":7200, "openid":"o4klh6sN5dXO-x7tK1e90n9rwX6Q", "refresh_token":"44_hXITXgDla98yluio7Evu0WxT3f2VUvVwCtmToeYU37hQI5opgnv7Rbt35oWj0mmy3pNC3hBZGBjxnZ9G_oqnZg", "scope":"snsapi_userinfo"}
	fmt.Printf("%#v\n", res)

	// 拉取用户信息：https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

	r2, _ := req.Get("https://api.weixin.qq.com/sns/userinfo", req.Param{
		"access_token": res["access_token"],
		"openid":       res["openid"],
		"lang":         "zh_CN",
	})

	var userinfo map[string]interface{}
	r2.ToJSON(&userinfo)
	// 正常返回数据
	c.JSON(
		200,
		utils.DealResponse(utils.Response{
			"data": userinfo,
		}),
	)
}

func SendTmpMsg(c *gin.Context) {
	r, _ := req.Get("https://api.weixin.qq.com/cgi-bin/token", req.Param{
		"appid":      "wxb86549d2232fa48d",
		"secret":     "a069fb164cc25ea91b9babdd0e994d58",
		"grant_type": "client_credential",
	})

	var res map[string]interface{}
	r.ToJSON(&res)
	fmt.Printf("token: %#v\n", res)

	// 拉取用户信息：https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
	payload := fmt.Sprintf(`
		{
			"touser":"%v",
			"template_id":"odZgVVI2jcVIMgqgLuxzDHoBFcnTdnSEHmDv4CJDsLI",
			"data":{
				"field1": {
					"value":"通过",
					"color":"#7FFF00"
				},
				"keyword2": {
					"value":"2021-5-10 11:55:20",
					"color":"#333333"
				},
				"text": {
					"value":"请到后台查看",
					"color":"#7FFF00"
				}
			}
		}
	`, "o4klh6sN5dXO-x7tK1e90n9rwX6Q")
	var body interface{}
	json.Unmarshal([]byte(payload), &body)
	fmt.Printf("body: %#v\n", body)
	r2, _ := req.Post("https://api.weixin.qq.com/cgi-bin/message/template/send", req.BodyJSON(&body), req.QueryParam{
		"access_token": res["access_token"],
	})

	var res2 map[string]interface{}
	r2.ToJSON(&res2)
	fmt.Printf("res2: %#v\n", res2)
	// 正常返回数据
	c.JSON(
		200,
		utils.DealResponse(utils.Response{
			"data": res2,
		}),
	)
}
